﻿using SSC.Models;
using SSC.Services;
using System.Windows;
using System.Windows.Threading;

namespace SSC.Views
{
    /// <summary>
    /// wdMaintenanceCheck.xaml 的交互逻辑
    /// </summary>
    public partial class wdMaintenanceCheck : Window
    {
        private readonly List<MaintenanceItemModel> _overdueItems;
        private UserService userService = new UserService();
        public wdMaintenanceCheck(List<MaintenanceItemModel> overdueItems)
        {
            InitializeComponent();
            _overdueItems = overdueItems;
            lstOverdueItems.ItemsSource = _overdueItems;
        }

        private void BtnConfirm_Click(object sender, RoutedEventArgs e)
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Password; // PasswordBox的密码

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("请输入用户名和密码！");
                return;
            }
            // 验证用户登录及权限
            var user = userService.QueryUserByName(username);
            if (user == null)
            {
                MessageBox.Show("用户不存在！");
                return;
            }
            if (user.UserPassword != password)
            {
                MessageBox.Show("密码错误！");
                return;
            }
            if (user.UserBackup == "1")
            {
                MessageBox.Show("权限不足，无法确认保养！");
                return;
            }
            //更新保养项目确认时间
            foreach (var item in _overdueItems)
            {
                item.LastMaintainAt = DateTime.Now; // 更新为当前时间
                MaintenanceService maintenanceService = new MaintenanceService();
                maintenanceService.UpdateItem(item);
            }
            var logService = new OperationLogService();
            logService.AddLog(username, "设备保养", "用户确认了保养项目");
            // 关闭当前窗口
            this.Close();
        }
    }
}
